/**
 * item controller
 */

import Promise from 'bluebird';
import BaseController from './base';

const itemBaseOptions = {
    ItemModel: null,

    components: {
        Uploader: require('../components/uploader'),
        VideoUploader: require('../components/video-uploader'),
        CodeEditor: require('../components/code-editor.vue'),
        DatePicker: require('../components/date-picker')
    },
    methods: {
        beforeLoadModel() {},
        afterLoadModel() {},
        loadModel(id) {
            return Promise.try(() => {
                return this.beforeLoadModel(id);
            })
            .then(() => {
                const itemModel = this.itemModel;
                if(id > 0) {
                    const query = Object.assign({
                        id: id
                    }, this.query);

                    return itemModel.$get(query);
                }

                return itemModel;
            })
            .tap(itemModel => {
                return this.afterLoadModel(itemModel);
            });
        },

        beforeSave(model) {
            return model;
        },
        afterSave() {
            this.$message.success('保存成功');

            this.$router.back();
        },
        save() {
            const itemModel = this.itemModel;

            return Promise.try(() => {
                return this.beforeSave(itemModel);
            })
            .then(data => {
                if(itemModel.id) {
                    return itemModel.$update(data);
                }

                return itemModel.$save(data);
            })
            .then(res => {
                return this.afterSave(res);
            });
        }
    },
    created() {
        const id = +this.$route.params.id || 0;

        this.loadModel(id);
    }
};

class ItemController extends BaseController {
    constructor(options) {
        const ret = super(options);

        if(!ret.mixins) {
            ret.mixins = [];
        }

        ret.mixins.push(itemBaseOptions);

        return ret;
    }
}

export default ItemController;
